//
//  UIColor.swift
//  Networking
//
//  Created by 许必成 on 2020/7/22.
//  Copyright © 2020年 东信北邮信息技术有限公司. All rights reserved.
//

import UIKit

public enum UIColorInputError : Error {
    case missingHashMarkAsPrefix,
    unableToScanHexValue,
    mismatchedHexStringLength,
    unableToOutputHexStringForWideDisplayColor
}

extension UIColor {

    /// 颜色的简写三位十六进制表示。#RGB定义为颜色#RRGGBB
    ///
    /// - Parameters:
    ///   - hex3: 三位十六进制值。
    ///   - alpha: 0.0 - 1.0。 默认值是1.0。
    public convenience init(hex3: UInt16, alpha: CGFloat = 1) {
        let divisor = CGFloat(15)
        let red     = CGFloat((hex3 & 0xF00) >> 8) / divisor
        let green   = CGFloat((hex3 & 0x0F0) >> 4) / divisor
        let blue    = CGFloat( hex3 & 0x00F      ) / divisor
        self.init(red: red, green: green, blue: blue, alpha: alpha)
    }

    /// 带有alpha的颜色的简写四位十六进制表示。#RGBA定义为颜色#RRGGBBAA。
    ///
    /// - parameter hex4: 四位十六进制值。
    public convenience init(hex4: UInt16) {
        let divisor = CGFloat(15)
        let red     = CGFloat((hex4 & 0xF000) >> 12) / divisor
        let green   = CGFloat((hex4 & 0x0F00) >>  8) / divisor
        let blue    = CGFloat((hex4 & 0x00F0) >>  4) / divisor
        let alpha   = CGFloat( hex4 & 0x000F       ) / divisor
        self.init(red: red, green: green, blue: blue, alpha: alpha)
    }

    /// 颜色的六位十六进制表示形式#RRGGBB。
    ///
    /// - Parameters:
    ///   - hex6: 六位十六进制值。
    ///   - alpha: 0.0 - 1.0。 默认值是1.0。
    public convenience init(hex6: UInt32, alpha: CGFloat = 1) {
        let divisor = CGFloat(255)
        let red     = CGFloat((hex6 & 0xFF0000) >> 16) / divisor
        let green   = CGFloat((hex6 & 0x00FF00) >>  8) / divisor
        let blue    = CGFloat( hex6 & 0x0000FF       ) / divisor
        self.init(red: red, green: green, blue: blue, alpha: alpha)
    }

    /// 色彩的六位十六进制表示形式为#RRGGBBAA。
    ///
    /// - Parameter hex8: 八位十六进制值。
    public convenience init(hex8: UInt32) {
        let divisor = CGFloat(255)
        let red     = CGFloat((hex8 & 0xFF000000) >> 24) / divisor
        let green   = CGFloat((hex8 & 0x00FF0000) >> 16) / divisor
        let blue    = CGFloat((hex8 & 0x0000FF00) >>  8) / divisor
        let alpha   = CGFloat( hex8 & 0x000000FF       ) / divisor
        self.init(red: red, green: green, blue: blue, alpha: alpha)
    }

    /// 带格式为＃RRGGBBAA /＃RRGGBB的alpha的颜色的rgba字符串表示形式会引发错误。
    ///
    /// - Parameter rgba: 字符串值
    public convenience init(rgba_throws rgba: String) throws {
        guard rgba.hasPrefix("#") else {
            throw UIColorInputError.missingHashMarkAsPrefix
        }
        
        let hexString: String = String(rgba[String.Index.init(encodedOffset: 1)...])
        var hexValue:  UInt32 = 0
        
        guard Scanner(string: hexString).scanHexInt32(&hexValue) else {
            throw UIColorInputError.unableToScanHexValue
        }
        
        switch (hexString.count) {
        case 3:
            self.init(hex3: UInt16(hexValue))
        case 4:
            self.init(hex4: UInt16(hexValue))
        case 6:
            self.init(hex6: hexValue)
        case 8:
            self.init(hex8: hexValue)
        default:
            throw UIColorInputError.mismatchedHexStringLength
        }
    }

    ///  使用形式为＃RRGGBBAA /＃RRGGBB的alpha的颜色的rgba字符串表示形式无法使用默认颜色。
    ///
    /// - Parameters:
    ///   - rgba: 字符串值
    ///   - defaultColor: 默认颜色
    public convenience init(_ rgba: String, defaultColor: UIColor = UIColor.clear) {
        guard let color = try? UIColor(rgba_throws: rgba) else {
            self.init(cgColor: defaultColor.cgColor)
            return
        }
        self.init(cgColor: color.cgColor)
    }

    /// UIColor实例的十六进制字符串，会引发错误。
    ///
    /// - Parameter includeAlpha: 是否应该包括alpha。
    public func hexStringThrows(_ includeAlpha: Bool = true) throws -> String  {
        var r: CGFloat = 0
        var g: CGFloat = 0
        var b: CGFloat = 0
        var a: CGFloat = 0
        self.getRed(&r, green: &g, blue: &b, alpha: &a)
        
        guard r >= 0 && r <= 1 && g >= 0 && g <= 1 && b >= 0 && b <= 1 else {
            throw UIColorInputError.unableToOutputHexStringForWideDisplayColor
        }
        
        if (includeAlpha) {
            return String(format: "#%02X%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255), Int(a * 255))
        } else {
            return String(format: "#%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255))
        }
    }
    
    /// UIColor实例的十六进制字符串，未能清空字符串。
    ///
    /// - Parameter includeAlpha: 是否应该包括alpha。
    /// - Returns:
    public func hexString(_ includeAlpha: Bool = true) -> String  {
        guard let hexString = try? hexStringThrows(includeAlpha) else {
            return ""
        }
        return hexString
    }
}

extension String {
    /// 将argb字符串转换为rgba字符串。
    public func argb2rgba() -> String? {
        guard self.hasPrefix("#") else {
            return nil
        }
        
        let hexString: String = String(self[self.index(self.startIndex, offsetBy: 1)...])
        switch hexString.count {
        case 4:
            return "#\(String(hexString[self.index(self.startIndex, offsetBy: 1)...]))\(String(hexString[..<self.index(self.startIndex, offsetBy: 1)]))"
        case 8:
            return "#\(String(hexString[self.index(self.startIndex, offsetBy: 2)...]))\(String(hexString[..<self.index(self.startIndex, offsetBy: 2)]))"
        default:
            return nil
        }
    }
}
/*
 // Solid color
 let strokeColor = UIColor("#FFCC00").CGColor
 
 // Color with alpha
 let fillColor = UIColor("#FFCC00DD").CGColor
 
 // Supports shorthand 3 character representation
 let backgroundColor = UIColor("#FFF")
 
 // Supports shorthand 4 character representation (with alpha)
 let menuTextColor = UIColor("#013E")
 
 // "#FF0000FF"
 let hexString = UIColor.redColor().hexString()
 
 // Convert shorthand 4 character representation (with alpha) from argb to rgba
 if let rgba = "#AFFF".argb2rgba() {
    let androidBackgroundColor = UIColor(rgba)
 }
 
 // Convert 8 character representation (with alpha) from argb to rgba
 if let rgba = "#AAFFFFFF".argb2rgba() {
    let androidFrontColor = UIColor(rgba)
 }
 */



